<template>
    <div v-show="stepValue === 2" class="phone-wrap">
        <Transition mode="out-in" name="el-fade-in-linear">
            <ZwPhonePreview
                v-show="props.phonePreviewIndex === 0"
                re-key="staffWelcome"
                :is-group-chat="false"
                class="activit-phone-welcome-preview" />
        </Transition>
        <Transition mode="out-in" name="el-fade-in-linear">
            <ZwPhonePreview
                v-show="props.phonePreviewIndex === 1"
                re-key="groupchatWelcome"
                :is-group-chat="true"
                class="activit-phone-welcome-preview" />
        </Transition>
        <Transition mode="out-in" name="el-fade-in-linear">
            <poster-phone
                v-show="props.phonePreviewIndex === 2"
                ref="activityPhoneRef"
                v-model:url="formParams.poster.absolute_url"
                class="poster-phone"
                :poster-head="formParams.poster.avatar_type"
                :poster-head-switch="formParams.poster.avatar_flag"
                :poster-nickname-color="formParams.poster.nickname_color"
                :poster-nickname-size="formParams.poster.nickname_size"
                :poster-nickname-switch="formParams.poster.nickname_flag"
                :poster-desc-color="formParams.poster.desc_color"
                :poster-desc-switch="formParams.poster.desc_flag"
                :poster-desc-content="formParams.poster.desc"
                :poster-desc-size="formParams.poster.desc_size" />
        </Transition>
        <div class="change-phone-index">
            <div :class="{ disabled: phonePreviewIndex <= 0 }" @click="changePhonePreviewIndex('up')">
                <img src="@/assets/phonePreview/activityPhonePreview/groupFission/up.png" />
            </div>
            <div :class="{ disabled: phonePreviewIndex >= 2 }" @click="changePhonePreviewIndex('down')">
                <img src="@/assets/phonePreview/activityPhonePreview/groupFission/down.png" />
            </div>
        </div>
    </div>
    <div id="activityGroupFissionPhone">
        <activity-phone
            v-show="stepValue !== 2"
            ref="activityGroupFissionPhoneRef"
            class="activity-h5-phone"
            width="340px"
            :scale="0.9">
            <div class="activity-phone-title">
                <el-icon><CloseBold /></el-icon>
                <strong>{{ formParams.activity_name || '活动名称' }}</strong>
            </div>
            <div id="phoneHeader" class="activity-phone-top">
                <!-- 滚动弹幕 -->
                <div v-show="showBarrageRollList()" id="barrageRoll" class="activity-phone-barrage-roll">
                    <div v-for="item in winnersList.slice(0, 4)" :key="item.name" class="barrage-roll-item">
                        <div>恭喜</div>
                        <div class="barrage-roll-info">
                            <img class="el-image" src="@/assets/smartMarketing/nomal_avatar.png" />
                            <span>{{ item.name }}**</span>
                            <span>
                                获得
                                <span class="barrage-roll-prize">{{ item.prize }}</span>
                            </span>
                        </div>
                    </div>
                </div>
                <!-- 轮播弹幕 -->
                <div
                    v-show="showBarrageLoopList()"
                    id="barrageLoop"
                    class="activity-phone-barrage-loop activity-phone-barrage-roll">
                    <div v-for="item in winnersList.slice(0, 5)" :key="item.name" class="barrage-roll-item">
                        <div>恭喜</div>
                        <div class="barrage-roll-info">
                            <img class="el-image" src="@/assets/smartMarketing/nomal_avatar.png" />
                            <span>{{ item.name }}**</span>
                            <span>
                                获得
                                <span class="barrage-roll-prize">{{ item.prize }}</span>
                            </span>
                        </div>
                    </div>
                </div>
                <!-- 头像昵称 -->
                <div class="top-user-info">
                    <img class="el-image" src="@/assets/phonePreview/activityPhonePreview/groupFission/ui-avatar.png" />
                    <span>客易达</span>
                </div>
                <div class="top-rule-anchor">活动规则</div>
            </div>
            <div class="activity-phone-main-body">
                <!-- 倒计时 -->
                <div class="main-count-down">
                    <!-- el-countdown是2.2.30版本的组件 -->
                    <div v-show="isCountDownFinish" class="countdown-desc">活动已结束</div>
                    <el-countdown
                        v-show="!isCountDownFinish"
                        format="活动倒计时: DD天HH时mm分ss秒"
                        :value="countdownValue"
                        @finish="handleFinish" />
                </div>

                <!-- 助力进度条 -->
                <div class="main-progress main-card">
                    <!-- 助力标题 -->
                    <strong class="prgress-title">
                        <aside class="decorate"></aside>
                        再邀请
                        <span class="help-num">
                            {{ computedTotalHelpNum() }}
                        </span>
                        位好友可得全部奖品
                        <aside class="decorate"></aside>
                    </strong>
                    <!-- 进度条 -->
                    <div class="help-progress">
                        <div v-for="item in formParams.reward_list.length + 1" :key="item" class="prize">
                            <img
                                class="el-image"
                                draggable="false"
                                src="@/assets/phonePreview/activityPhonePreview/groupFission/prize.png" />
                        </div>
                    </div>
                    <el-button class="help-button">邀请好友助力</el-button>
                </div>

                <!-- 奖品列表 -->
                <div class="main-prize-list main-card">
                    <div class="prize-title">
                        <img
                            class="el-image"
                            src="@/assets/phonePreview/activityPhonePreview/groupFission/prize2.png" />
                        活动奖品
                    </div>
                    <div class="prize-list">
                        <div v-for="(item, index) in formParams.reward_list" :key="index" class="prize-item">
                            <el-image :src="item.reward_image" />
                            <div class="prize-info">
                                <div class="zw-text-ellipsis">{{ item.reward_title }}</div>
                                <div v-show="isOpen(formParams.inventory_show_switch)" class="prize-stock-num">
                                    剩余{{ item.reward_stock }}件
                                </div>
                                <div>
                                    <el-progress :percentage="computedPercentage(item.help_num)">
                                        <span class="help-percentage">{{ computedHelpNum(item.help_num) }}</span>
                                        <span class="help-target">/{{ item.help_num }}</span>
                                    </el-progress>
                                </div>
                            </div>
                            <div class="prize-operate">
                                <el-button v-if="item.help_num - DEFAULE_HELP_NUM <= 0">去领取</el-button>
                                <el-button v-else class="help-num-button">
                                    还差{{ item.help_num - DEFAULE_HELP_NUM }}人
                                </el-button>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- 活动信息tab切换 -->
                <div id="activilyTabs" class="main-tabs main-card">
                    <el-tabs v-model="activilyTabsActived">
                        <el-tab-pane
                            v-if="isOpen(formParams.activity_info_switch)"
                            label="活动信息"
                            name="activilyInfo">
                            <div class="activity-info-content" v-html="formParams.activity_info_content"></div>
                        </el-tab-pane>
                        <el-tab-pane label="助力好友" name="helpFrend">
                            <div v-for="item in 2" :key="item" class="help-firend-item">
                                <div>{{ item }}</div>
                                <div class="help-friend-info">
                                    <img
                                        class="el-image"
                                        src="@/assets/phonePreview/activityPhonePreview/groupFission/ui-avatar1.png" />
                                    <span>微信好友{{ item }}</span>
                                </div>
                                <div class="help-friend-time">03-10 13:{{ item }}0:00</div>
                            </div>
                            <div class="nomore">没有更多了</div>
                        </el-tab-pane>
                        <!-- 中奖轮播为页面滚动时打开 -->
                        <el-tab-pane
                            v-if="isOpen(formParams.win_prize_loop_switch) && formParams.win_prize_loop_type === 1"
                            label="中奖名单"
                            name="winnersList">
                            <div v-for="item in winnersList" :key="item.name" class="winner-item">
                                <div>恭喜</div>
                                <div class="winner-info">
                                    <img class="el-image" src="@/assets/smartMarketing/nomal_avatar.png" />
                                    <span>{{ item.name }}**</span>
                                    <span>
                                        获得
                                        <span class="winner-prize">{{ item.prize }}</span>
                                    </span>
                                </div>
                            </div>
                        </el-tab-pane>
                    </el-tabs>
                </div>

                <!-- 活动规则 -->
                <div class="main-rule main-card">
                    <div class="rule-title">
                        <img
                            class="el-image"
                            src="@/assets/phonePreview/activityPhonePreview/groupFission/explain.png" />
                        活动规则
                    </div>
                    <div class="rule-desc">
                        <div class="rule-label">活动时间</div>
                        <div v-if="formParams.period_type === 1" class="rule-content">永久</div>
                        <div v-else class="rule-content">
                            {{ formParams.activity_time?.join?.('至') }}
                        </div>
                    </div>
                    <div class="rule-desc">
                        <div class="rule-label">活动说明</div>
                        <div class="rule-content" v-html="handleReplaceDesc(formParams.description)"></div>
                    </div>
                </div>
            </div>
        </activity-phone>
    </div>
</template>

<script setup lang="ts">
import { ref, watch, computed, nextTick } from 'vue';
import moment from 'moment';
import { sum } from 'lodash';
import Decimal from 'decimal.js';
import activityPhone from '@/components/zw/phonePreview1.0/activityPhonePreview/index.vue';
import phonePreview from '@/components/zw/phonePreview1.0/welcomePhonePreview/materialPreview/index.vue';
import posterPhone from '@/components/zw/phonePreview1.0/activityPhonePreview/posterPhone/index.vue';

import { isOpen } from './utils/index';
import { formParams, stepValue } from './utils/paramsManager';
import { IActivilyTabsActived, ISwitchKey } from './utils/interface';

const props = defineProps({
    // 第三步欢迎语的样机索引
    phonePreviewIndex: {
        type: Number,
        default: 0
    }
});

const emit = defineEmits(['update:phonePreviewIndex']);

/* ----------------------------倒计时-start---------------------------- */
// 默认18天8小时28分钟28秒的倒计时
const defaultCountDown = moment().add(18, 'days').add(8, 'hours').add(28, 'minutes').add(28, 'seconds');
// 倒计时的值
const countdownValue = computed(() => {
    if (formParams.period_type === 1 || !formParams.activity_time?.[1]) {
        return defaultCountDown;
    }
    return moment().add(moment(formParams.activity_time[1]).diff(moment()));
});

watch(
    () => formParams.activity_time,
    () => {
        isCountDownFinish.value = false;
    }
);

/** 倒计时是否结束 */
const isCountDownFinish = ref(false);
// 倒计时结束需要更改字段
const handleFinish = () => {
    isCountDownFinish.value = true;
};
/* ----------------------------倒计时-end---------------------------- */

/* ----------------------------滚动-start---------------------------- */
const changePhonePreviewIndex = (changeType: 'up' | 'down') => {
    if (changeType === 'up') {
        emit('update:phonePreviewIndex', props.phonePreviewIndex - 1 < 0 ? 0 : props.phonePreviewIndex - 1);
    } else {
        emit('update:phonePreviewIndex', props.phonePreviewIndex + 1 > 2 ? 2 : props.phonePreviewIndex + 1);
    }
};
/* ----------------------------滚动-end---------------------------- */

/* ----------------------------样机-start---------------------------- */
/**
 * @description 默认已经助力的人数
 */
const DEFAULE_HELP_NUM = 2;
/**
 * 计算助力总人数
 */
const computedTotalHelpNum = () => {
    return sum(formParams.reward_list.map(item => item.help_num));
};

/**
 * 计算奖品助力的人数
 */
const computedHelpNum = (helpNum = 0) => {
    return DEFAULE_HELP_NUM > helpNum ? helpNum : DEFAULE_HELP_NUM;
};

/**
 * 计算奖品助力的进度
 */
const computedPercentage = (helpNum = 0) => {
    return Number(Decimal.div(DEFAULE_HELP_NUM, helpNum)) * 100;
};

/**
 * @description 替换描述的左右尖括号，把/n替换成换行
 * @param val
 */
const handleReplaceDesc = (val: string) => {
    const result = val.replace(/\</g, '&lt;').replace(/\>/g, '&gt;').replace(/\n/g, '<br />');
    return result;
};

// 中奖名单的内容
const winnersList = [
    { name: '大', prize: '一等奖' },
    { name: '大事情', prize: '二等奖' },
    { name: '小事情', prize: '三等奖' },
    { name: '常青藤', prize: '三等奖' },
    { name: '常青藤', prize: '三等奖' }
];

/**
 * tabs栏当前选中的，默认是助力好友
 * 切换开关时，动态变更选中的tabs
 */
const activilyTabsActived = ref<IActivilyTabsActived>('helpFrend');
/** 外部设置当前激活的标签栏 */
const setActivilyTabsActived = (val?: IActivilyTabsActived | string) => {
    if (!val) {
        activilyTabsActived.value = 'helpFrend';
        return;
    }

    // 如果是IActivilyTabsActived类型的值，则直接打开到tabs
    if (isIActivilyTabsActived(val)) {
        activilyTabsActived.value = val;
        toScrollView('#activilyTabs');
        return;
    }

    // 如果不是设置IActivilyTabsActived类型的值，并且当前选中的是活动信息
    // 则到默认信息。如果默认信息没有开，则到助力好友
    if (isOpen(formParams.activity_info_switch) && activilyTabsActived.value === 'activilyInfo') {
        activilyTabsActived.value = 'activilyInfo';
        return;
    }

    toScrollView(val);
    activilyTabsActived.value = 'helpFrend';
};

/**
 * 判断是否是IActivilyTabsActived类型的值
 * @param value string
 */
const isIActivilyTabsActived = (value: string): value is IActivilyTabsActived => {
    return ['activilyInfo', 'helpFrend', 'winnersList'].includes(value);
};

/**
 * 让某个元素滚动至dom的视图上
 * @param selector 选择器字符串
 */
const toScrollView = async (selector: string, behavior: 'smooth' | 'auto' = 'smooth') => {
    await nextTick();
    const element = document.querySelector(selector);
    if (!element) {
        return;
    }
    element.scrollIntoView({ behavior, block: 'center', inline: 'center' });
};

/**
 * 滚动弹幕是否展示
 * @returns {boolean} formParams.win_prize_loop_type === 2
 */
const showBarrageRollList = () => {
    return isOpen(formParams.win_prize_loop_switch) && formParams.win_prize_loop_type === 2;
};

/**
 * 轮播弹幕是否展示
 * @returns {boolean} formParams.win_prize_loop_type === 3
 */
const showBarrageLoopList = () => {
    return isOpen(formParams.win_prize_loop_switch) && formParams.win_prize_loop_type === 3;
};

const activityGroupFissionPhoneRef = ref();
watch(stepValue, async (newValue: number) => {
    if (newValue === 0) {
        // 第一步判断是否打开了活动信息，如果打开了则展示活动信息页面
        if (isOpen(formParams.activity_info_switch)) {
            setActivilyTabsActived('activilyInfo');
            return;
        }
    } else if (newValue === 3) {
        // 最后一部判断当前弹幕的位置
        if (isOpen(formParams.win_prize_loop_switch) && formParams.win_prize_loop_type === 1) {
            setActivilyTabsActived('winnersList');
            return;
        }
    }
    await nextTick();
    toScrollView('#phoneHeader', 'auto');
});
/* ----------------------------样机-end---------------------------- */

/* ----------------------------海报位置-start---------------------------- */
const activityPhoneRef = ref<any>(null);

/** 获取海报位置 */
const getPostersInfo = () => {
    return activityPhoneRef.value.formData;
};

/** 设置海报位置 */
const setPostersInfo = (data: any) => {
    Object.assign(activityPhoneRef.value.formData.position, data);
};

/* ----------------------------海报位置-end---------------------------- */
defineExpose({
    getPostersInfo,
    setPostersInfo,
    setActivilyTabsActived
});
</script>

<style lang="scss" scoped>
@import './styles/activity-phone';
</style>
